package com.example.managemyself.ui.ai;

import android.app.AlertDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.SearchView;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.managemyself.R;
import com.example.managemyself.data.model.AIConversation;
import com.example.managemyself.data.model.User;
import com.example.managemyself.util.UserManager;
// import com.example.managemyself.viewmodel.AIViewModel;
import com.google.android.material.chip.Chip;
import com.google.android.material.chip.ChipGroup;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.List;

/**
 * AI历史记录Fragment
 */
public class AIHistoryFragment extends Fragment implements AIHistoryAdapter.OnConversationClickListener {
    
    private RecyclerView recyclerView;
    private AIHistoryAdapter adapter;
    private ChipGroup chipGroupCategories;
    private FloatingActionButton fabNewChat;
    
    // private AIViewModel viewModel;
    private List<AIConversation> allConversations = new ArrayList<>();
    private String currentCategory = "全部";
    private String currentSearchQuery = "";
    
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }
    
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_ai_history, container, false);
    }
    
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        
        initViews(view);
        // setupViewModel();
        setupRecyclerView();
        setupCategories();
        // loadData();
        
        // 显示开发中提示
        Toast.makeText(requireContext(), "AI历史记录功能开发中", Toast.LENGTH_LONG).show();
    }
    
    private void initViews(View view) {
        recyclerView = view.findViewById(R.id.recycler_view_history);
        chipGroupCategories = view.findViewById(R.id.chip_group_categories);
        fabNewChat = view.findViewById(R.id.fab_new_chat);
        
        fabNewChat.setOnClickListener(v -> startNewChat());
    }
    
    // private void setupViewModel() {
    //     viewModel = new ViewModelProvider(this).get(AIViewModel.class);
    // }
    
    private void setupRecyclerView() {
        adapter = new AIHistoryAdapter(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
        recyclerView.setAdapter(adapter);
    }
    
    private void setupCategories() {
        // 添加默认分类
        String[] categories = {"全部", "任务", "健康", "日记", "其他", "收藏"};
        
        for (String category : categories) {
            Chip chip = new Chip(requireContext());
            chip.setText(category);
            chip.setCheckable(true);
            chip.setOnClickListener(v -> filterByCategory(category));
            
            if (category.equals("全部")) {
                chip.setChecked(true);
            }
            
            chipGroupCategories.addView(chip);
        }
    }
    
    private void filterByCategory(String category) {
        currentCategory = category;
        
        // 更新chip状态
        for (int i = 0; i < chipGroupCategories.getChildCount(); i++) {
            Chip chip = (Chip) chipGroupCategories.getChildAt(i);
            chip.setChecked(chip.getText().toString().equals(category));
        }
        
        filterConversations();
    }
    
    private void filterConversations() {
        // 暂时显示空列表
        adapter.updateConversations(new ArrayList<>());
    }
    
    private void startNewChat() {
        Navigation.findNavController(requireView()).navigate(R.id.action_aiHistoryFragment_to_aiChatFragment);
    }
    
    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        inflater.inflate(R.menu.ai_history_menu, menu);
        
        MenuItem searchItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) searchItem.getActionView();
        
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }
            
            @Override
            public boolean onQueryTextChange(String newText) {
                currentSearchQuery = newText;
                filterConversations();
                return true;
            }
        });
    }
    
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int itemId = item.getItemId();
        
        if (itemId == R.id.action_clear_all) {
            Toast.makeText(requireContext(), "清除功能开发中", Toast.LENGTH_SHORT).show();
            return true;
        } else if (itemId == R.id.action_export) {
            exportHistory();
            return true;
        }
        
        return super.onOptionsItemSelected(item);
    }
    
    private void exportHistory() {
        Toast.makeText(requireContext(), "导出功能开发中", Toast.LENGTH_SHORT).show();
    }
    
    // AIHistoryAdapter.OnConversationClickListener 实现
    @Override
    public void onConversationClick(AIConversation conversation) {
        Bundle args = new Bundle();
        args.putInt("conversation_id", conversation.getId());
        Navigation.findNavController(requireView()).navigate(R.id.action_aiHistoryFragment_to_aiChatFragment, args);
    }
    
    @Override
    public void onConversationLongClick(AIConversation conversation) {
        showConversationOptions(conversation);
    }
    
    @Override
    public void onStarClick(AIConversation conversation) {
        Toast.makeText(requireContext(), "收藏功能开发中", Toast.LENGTH_SHORT).show();
    }
    
    private void showConversationOptions(AIConversation conversation) {
        String[] options = {"重命名", "删除", conversation.isStarred() ? "取消收藏" : "收藏"};
        
        new AlertDialog.Builder(requireContext())
                .setTitle(conversation.getTitle())
                .setItems(options, (dialog, which) -> {
                    switch (which) {
                        case 0: // 重命名
                            showRenameDialog(conversation);
                            break;
                        case 1: // 删除
                            confirmDeleteConversation(conversation);
                            break;
                        case 2: // 收藏/取消收藏
                            Toast.makeText(requireContext(), "收藏功能开发中", Toast.LENGTH_SHORT).show();
                            break;
                    }
                })
                .show();
    }
    
    private void showRenameDialog(AIConversation conversation) {
        Toast.makeText(requireContext(), "重命名功能开发中", Toast.LENGTH_SHORT).show();
    }
    
    private void confirmDeleteConversation(AIConversation conversation) {
        Toast.makeText(requireContext(), "删除功能开发中", Toast.LENGTH_SHORT).show();
    }
} 